package config;

import com.alibaba.druid.pool.DruidDataSource;
import com.dao.impl.DbConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan("com")
@PropertySource("classpath:db.properties")
@EnableTransactionManagement() // 事务（transaction）：第一步
//@Import(TransactionManagementConfigurationSelector.class)
public class AppConfig {

    @Autowired
    private DbConfig dbConfig;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dbConfig.getUrl());
        dataSource.setUsername(dbConfig.getUsername());
        dataSource.setPassword(dbConfig.getPassword());
        dataSource.setDriverClassName(dbConfig.getDriverClassName());
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate template = new JdbcTemplate(dataSource());
        return template;
    }

    //事务第二步：注册事务管理器，基本就一个DataSourceTransactionManager
    @Bean
    public PlatformTransactionManager transactionManager() {
        //这里用的dataSource，必须跟你操作数据库用的dataSource是同一个
        DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource());
        return txManager;
    }
}
